package net.jjjshop.common.service.lbt.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.jjjshop.common.cache.RedisUtil;
import net.jjjshop.common.constants.ConfConstants;
import net.jjjshop.common.constants.TaskConstants;
import net.jjjshop.common.entity.lbt.LbLineUp;
import net.jjjshop.common.entity.lbt.LbLotteryOrder;
import net.jjjshop.common.entity.lbt.LbSysConfigEntity;
import net.jjjshop.common.entity.lbt.LbUserWalletEntity;
import net.jjjshop.common.entity.order.Order;
import net.jjjshop.common.entity.order.OrderAddress;
import net.jjjshop.common.entity.order.OrderProduct;
import net.jjjshop.common.entity.product.Product;
import net.jjjshop.common.entity.supplier.Supplier;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.mapper.user.UserMapper;
import net.jjjshop.common.service.lbt.*;
import net.jjjshop.common.service.order.OrderAddressService;
import net.jjjshop.common.service.order.OrderProductService;
import net.jjjshop.common.service.order.OrderService;
import net.jjjshop.common.service.product.ProductService;
import net.jjjshop.common.service.supplier.SupplierService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.BigDecimalUtil;
import net.jjjshop.framework.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@EnableAsync
@Service
public class BuyProductSettlementServiceImpl extends BuyProductSettlementService {

    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserBillService userBillService;

    @Autowired
    private LbLineUpService lineUpService;

    private static final Logger logger = LoggerFactory.getLogger(BuyProductSettlementServiceImpl.class);

    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private UserMapper userMapper;
//    @Autowired
//    private UserGradeService userGradeService;



    @Autowired
    private LbSysConfigService sysConfigService;
    @Resource
    private LbUserWalletService walletService;

    @Autowired
    private OrderAddressService addressService;


    @Autowired
    private LbLotteryOrderService lotteryOrderService;

    @Override
    public Boolean orderReceiving(Integer orderId) {
        try {


        logger.info(orderId+"订单开始做结算咯");
        Order storeOrder = orderService.getById(orderId);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new BusinessException(StrUtil.format("订单收货task处理，未找到订单，id={}", orderId));
        }
        List<OrderProduct> orderInfoList = orderProductService.getProductList(storeOrder.getOrderId());
        if (null == orderInfoList || orderInfoList.isEmpty()){
            throw new BusinessException("未找订单产品信息");
        }

        String redisKey = TaskConstants.ORDER_HANDLE;
        List<Object> list = redisUtil.lRange(redisKey, 0, -1);
        if (null != list){
            if (list.contains(orderId)){
                logger.info(orderId+"订单重复结算了哦");
                return true;
            }
        }
        Supplier supplier = supplierService.getById(storeOrder.getShopSupplierId());

        BigDecimal payPrice = storeOrder.getPayPrice();
        Integer uid = storeOrder.getUserId();
        User walletInfo = userService.getById(uid);

            walletInfo.setOrderNum(walletInfo.getOrderNum()+1);
            walletInfo.setOrderNum(walletInfo.getOrderNum()+1);
            if (walletInfo.getZtOrderNum()>=2){
                walletInfo.setGradeId(3);
            }else{
                walletInfo.setGradeId(2);
            }
        redisUtil.lPush(redisKey, orderId);
            //添加分红池
            LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
            BigDecimal xDa = new BigDecimal(0.05);//下单百分之5分红池
            BigDecimal fhPrice = BigDecimalUtil.mul(payPrice, xDa);
            BigDecimal welfare = BigDecimalUtil.mul(payPrice, new BigDecimal(0.01));
            lbSysConfigEntity.setWelfare(BigDecimalUtil.addDouble(welfare,lbSysConfigEntity.getWelfare()));
//            lbSysConfigEntity.setDividendPool(BigDecimalUtil.addDouble(fhPrice,lbSysConfigEntity.getDividendPool()));
//            clGpMeth(fhPrice,orderId);
            sysConfigService.updateById(lbSysConfigEntity);
            logger.info(orderId+"更新分红池");
        if (null != supplier){
            logger.info(orderId+"订单的商家查询");
            //公排商家
            if (supplier.getShopType().intValue() == 1){
                logger.info(orderId+"商家为公排订单");
                if (null ==walletInfo.getPid() && walletInfo.getRefereeId()!=null){
//
                    setPidInfo(walletInfo,userService.getById(walletInfo.getRefereeId()));
                }
                goGpOderInfo(storeOrder,orderInfoList,walletInfo,orderId,storeOrder.getPayType());
                return true;
            }else  if (supplier.getShopType().intValue() == 2){
                logger.info(orderId+"第三个模块下单模式");
                if (null ==walletInfo.getPid() && walletInfo.getRefereeId()!=null){
//
                    setPidInfo(walletInfo,userService.getById(walletInfo.getRefereeId()));
                }
                threeMode(storeOrder,walletInfo,orderId,storeOrder.getPayType());
                return true;
            }else  if (supplier.getShopType().intValue() == 3){
                logger.info(orderId+"第4个模块下单模式");
                if (null ==walletInfo.getLevel4() || walletInfo.getLevel4() ==-1){
                    walletInfo.setLevel4(0);
                }
                if (null ==walletInfo.getPid() && walletInfo.getRefereeId()!=null){
//
                    setPidInfo(walletInfo,userService.getById(walletInfo.getRefereeId()));
                }
                fourMode(storeOrder,orderInfoList,walletInfo,orderId,storeOrder.getPayType());
                return true;
            }
        }


//        userBillService.addBillRecord("消费分红贡献",ConfConstants.DIVIDEND_POOL,1,fhPrice,uid,2,orderId);


        sendQyk(new BigDecimal("0.5"),uid,orderId);
        LbUserWalletEntity qb = walletService.getUserWalletInfo(uid);
        qb.setDevote(BigDecimalUtil.addDouble(qb.getDevote(),BigDecimalUtil.mul(payPrice,new BigDecimal(10))));
        if (qb.getDjMoney().doubleValue() >0){
            logger.info(orderId+"佣金冻结结算处理");
            BigDecimal a = null;
            if (qb.getDevote().doubleValue() > qb.getDjMoney().doubleValue()){

                //释放冻结佣金
                a = qb.getDjMoney();
                qb.setDjMoney(new BigDecimal(0));
                qb.setDevote(BigDecimalUtil.subDouble(qb.getDevote(),qb.getDjMoney()));

            }else{
                BigDecimal b = BigDecimalUtil.subDouble(qb.getDjMoney(),qb.getDevote());
                a = qb.getDevote();
                qb.setDjMoney(b);
                qb.setDevote(new BigDecimal(0));
            }

//            userBillService.saveBill("冻结佣金释放",ConfConstants.COMMISSION_TYPE,1,a,uid,ConfConstants.YJ_FLAG, orderId);
            if(a.doubleValue() >0) {
                BigDecimal aa = BigDecimalUtil.mul(a, new BigDecimal(1));
                BigDecimal bb = BigDecimalUtil.mul(a, new BigDecimal(0.1));
                BigDecimal total = BigDecimalUtil.addDouble(qb.getMoney(), aa);
//                    walletInfo.setEntityMoney(BigDecimalUtil.addDouble(walletInfo.getEntityMoney(), a));
                qb.setTotalMoney(BigDecimalUtil.addDouble(qb.getTotalMoney(), aa));
//                qb.setIntegral(BigDecimalUtil.addDouble(qb.getIntegral(),bb));
                qb.setMoney(total);
                userBillService.addBillRecord("冻结佣金释放", ConfConstants.COMMISSION_TYPE, 1, a, uid, 2,orderId);
            }
            logger.info(orderId+"佣金冻结结算处理完成");
        }
            walletService.updateById(qb);

//

        /**
         * 确认收货送积分
         */

//        String where = "paid = 1 and refund_status = 0 and uid = "+uid;
        //首单消费送积分,用户在前5000个才送积分
//        walletInfo.setPoints(BigDecimalUtil.addDouble(new BigDecimal(walletInfo.getPoints()),payPrice).intValue());
//        walletInfo.setAllAv(BigDecimalUtil.addDouble(walletInfo.getAllAv(),payPrice));
//        walletInfo.setFirstPay(BigDecimalUtil.addDouble(userSave.getFirstPay(),payPrice));
        userService.updateById(walletInfo);
//        }

        //直推直接算提成
        BigDecimal scale = new BigDecimal(0.1);//直推提成10%
        BigDecimal price = BigDecimalUtil.mul(payPrice, scale);
            logger.info(orderId+"直推奖励结算哦");
        userBillService.saveBill("直推奖励", ConfConstants.COMMISSION_TYPE,1, price, walletInfo.getRefereeId(),ConfConstants.YJ_FLAG,orderId);

//        }
//         marketPromotion(storeOrder);
        sendQyk(new BigDecimal("1"), walletInfo.getRefereeId(),orderId);
        if (null ==walletInfo.getPid() && walletInfo.getRefereeId()!=null){

            setPidInfo(walletInfo,userService.getById(walletInfo.getRefereeId()));
        }

//        User pUser = userService.getById(walletInfo.getPid());
            User pUser = getUs(walletInfo.getPid(),uid);

        if (null != pUser && pUser.getZtOrderNum()>=2){
//            BigDecimal scale1 = new BigDecimal(0.3);//财富奖提出
//            BigDecimal price1 = BigDecimalUtil.mul(payPrice, scale1);
//            userBillService.saveBill("销售绩效", ConfConstants.COMMISSION_TYPE,1, price1, pUser.getUserId(),ConfConstants.YJ_FLAG,orderId);
            jsCfMoney(pUser,payPrice,orderId,"财富奖励");
            if (null != pUser.getRefereeId()&&pUser.getRefereeId().intValue() >0 ){
                User reFer = userService.getById(pUser.getRefereeId());
                if (reFer.getZtOrderNum() >2){
                    jsCfMoney(reFer,payPrice,orderId,"平级奖励");
//                userBillService.saveBill("综合销售业绩", ConfConstants.COMMISSION_TYPE,1, price1, pUser.getRefereeId(),ConfConstants.YJ_FLAG,orderId);
                }
            }
        }

        //查询商家信息，查找商家推荐人，进行每一笔订单的奖励

            if (null != supplier){
                //计算成本给商家
                BigDecimal bs = BigDecimalUtil.mul(storeOrder.getPayPrice(),supplier.getCostRate());
                supplier.setMoney(BigDecimalUtil.addDouble(supplier.getMoney(),bs));
                supplierService.updateById(supplier);
                userBillService.saveBill("店铺补贴", ConfConstants.COMMISSION_TYPE,1, bs, supplier.getUserId(),ConfConstants.YJ_FLAG,orderId);
                if ( null != supplier.getTjPhone()){
                    User byAccount = userService.getByAccount(supplier.getTjPhone());
                    if (null != byAccount) {
                        //直推直接算提成
                        BigDecimal tshop = new BigDecimal(0.03);//推商家拿%2订单奖
                        BigDecimal uSy = BigDecimalUtil.mul(payPrice, tshop);
                        userBillService.saveBill("商家推荐产品收益奖", ConfConstants.COMMISSION_TYPE, 1, uSy, byAccount.getUserId(), ConfConstants.YJ_FLAG, orderId);
                    }
                }

            }
//        rangeReward(uid,storeOrder.getPayPrice(),orderId);


        return true;
        }catch (Exception e){
            logger.info(orderId+"订单结算异常："+e.getMessage());
            String key = TaskConstants.ORDER_HANDLE;
            redisUtil.getRightPop(key,10L);
            String redisKey = TaskConstants.ORDER_TASK_REDIS_KEY_AFTER_TAKE_BY_USER;
            redisUtil.lPush(redisKey,orderId);

            return false;
        }
        /**
         * 确认收货送积分end
         */
    }

    /**
     * 结算财富奖收益
     */
    private void jsCfMoney(User pUser,BigDecimal payPrice,Integer orderId,String msg){
        User A = null;
        User B = null;
        int a = 0;
            if (pUser.getAline() != null){
                 A = userService.getById(pUser.getAline());
                 if (null!=A && A.getZtOrderNum() >2){
                     a +=1;
                 }
            }
        if (pUser.getBline() != null){
           B = userService.getById(pUser.getBline());
            if (null!=B &&  B.getZtOrderNum() >2){
                a +=1;
            }
        }
        logger.info(orderId+"结算财富奖收益");
//        if (a >=2){
            LbUserWalletEntity qb = walletService.getUserWalletInfo(pUser.getUserId());
            if (null !=qb) {
                //全部结算
                BigDecimal scale1 = new BigDecimal(0.3);//财富奖提出
                BigDecimal price1 = BigDecimalUtil.mul(payPrice, scale1);
                userBillService.saveBill(msg, ConfConstants.COMMISSION_TYPE, 1, price1, pUser.getUserId(), ConfConstants.YJ_FLAG, orderId);
                if (qb.getCfMoney().doubleValue() > 0) {
                    userBillService.saveBill("财富奖励冻结释放", ConfConstants.COMMISSION_TYPE, 1, qb.getCfMoney(), pUser.getUserId(), ConfConstants.YJ_FLAG, orderId);
//                    qb.setCfMoney(new BigDecimal(0));
//                    walletService.updateById(qb);

                }
            }
            logger.info(orderId+"解冻财富收益");
//        }else{
//            BigDecimal scale1 = new BigDecimal(0.3);//财富奖提出
//            BigDecimal price1 = BigDecimalUtil.mul(payPrice, scale1);
//            BigDecimal price11 = BigDecimalUtil.mul(price1, new BigDecimal(0.5));
//            userBillService.saveBill(msg, ConfConstants.COMMISSION_TYPE,1, price1, pUser.getUserId(),ConfConstants.YJ_FLAG,orderId);
////            userBillService.saveBill(msg+"冻结", ConfConstants.WEALTH_DJ_TYPE,1, price11, pUser.getUserId(),ConfConstants.YJ_FLAG,orderId);
//            logger.info(orderId+"冻结财富收益");
//        }

    }


    private boolean setPidInfo(User byPhone,User userParent){
//        Boolean execute = transactionTemplate.execute(e -> {
//            User byPhone = getByPhone(user.getMobile());
        logger.info(byPhone.getUserId()+"安置区域");
            if (null == userParent.getAline()){
                byPhone.setPid(userParent.getUserId());
                userParent.setAline(byPhone.getUserId());
                userMapper.updateById(byPhone);
                userMapper.updateById(userParent);
            }else if (null == userParent.getBline()){
                byPhone.setPid(userParent.getUserId());
                userParent.setBline(byPhone.getUserId());
                userMapper. updateById(byPhone);
                userMapper.updateById(userParent);
            }else if (null == userParent.getCline()){
                byPhone.setPid(userParent.getUserId());
                userParent.setCline(byPhone.getUserId());
                userMapper.updateById(byPhone);
                userMapper.updateById(userParent);
            }else{
                //如果三条线都安置完成了后，就开始往C线的AB线安置
                return  setLineDs(byPhone,userParent.getCline());

            }
        logger.info(byPhone.getUserId()+"安置区域完毕");
            return Boolean.TRUE;
//        });
//        if (!execute) {
//            throw new BusinessException("创建用户失败!");
//        }
    }





    private boolean setLineDs(User byPhone,Integer cid){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cid);
        User userParent = userMapper.selectOne(queryWrapper);

        if (null == userParent.getAline()){
            byPhone.setPid(userParent.getUserId());
            userParent.setAline(byPhone.getUserId());
            userMapper.updateById(byPhone);
            userMapper.updateById(userParent);
            return true;
        }else if (null == userParent.getBline()){
            byPhone.setPid(userParent.getUserId());
            userParent.setBline(byPhone.getUserId());
            userMapper.updateById(byPhone);
            userMapper.updateById(userParent);
            return true;
        }else{

            int randomInt = ThreadLocalRandom.current().nextInt(2);
            //如果三条线都安置完成了后，就开始往C线的AB线安置
            if (randomInt == 0){
                return   setLineDs(byPhone,userParent.getAline());
            }else{
                return   setLineDs(byPhone,userParent.getBline());
            }


        }
    }

    /**
     * 寻找上一级C节点
     * @param pid
     * @return
     */
    private User getUs(Integer pid,Integer uid){
        User pUser = userService.getById(pid);
        if (null != pUser){
            if ( null !=pUser.getCline()&&uid.intValue() == pUser.getCline().intValue()){

                return pUser;
            }else {
             return    getUs(pUser.getPid(),pUser.getUserId());
            }

        }
        return null;

    }

    private void addGpIncome(User user,int pid){
        LambdaQueryWrapper<LbLineUp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LbLineUp::getPid,pid);
        wrapper.eq(LbLineUp::getUid,user.getUserId());
        wrapper.le(LbLineUp::getStatus,1);
        List<LbLineUp> list = lineUpService.list(wrapper);
        if (null != list && list.size() > 0){
            LbLineUp bean = list.get(0);
            if(bean.getPrice().doubleValue() >0){
                bean.setZtOrderNum(bean.getZtOrderNum()+1);
                int a = bean.getZtOrderNum().intValue();
//                if (a  >=10){
//                    a = 10;
//                }
                BigDecimal sbs = BigDecimalUtil.divide(new BigDecimal(a),new BigDecimal(10));
                bean.setTotal(BigDecimalUtil.addDouble(bean.getPrice(),BigDecimalUtil.mul(bean.getPrice(),sbs)));
                lineUpService.updateById(bean);
            }

        }
    }

    /**
     * 继续查找公排数据
     * @param sy
     */
    private void Gp(BigDecimal sy,Integer orderId,Integer pid){
//        LbLineUp lbLineUp = lbLineUpService.setUpOrder();
        LbLineUp status1 =lineUpService.setUpOrder(pid);
        if (null != status1){
            BigDecimal ts = BigDecimalUtil.addDouble(status1.getIncome(),sy);
            if (ts.doubleValue() >= status1.getTotal().doubleValue()){
                BigDecimal   dyPrice = BigDecimalUtil.subDouble(ts,status1.getTotal());
                status1.setStatus(2);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,BigDecimalUtil.subDouble(status1.getTotal(),status1.getIncome()) , status1.getUid(),null,orderId);
                status1.setIncome(status1.getTotal());
                lineUpService.updateById(status1);
                if (dyPrice.doubleValue() >0){
                    Gp(dyPrice,orderId,pid);
                }
            }else{
                status1.setIncome(ts);
                status1.setStatus(1);
                lineUpService.updateById(status1);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,sy , status1.getUid(),null,orderId);

            }
        }

    }



    @Async
    @Override
    public void rangeReward(Integer buyId,BigDecimal payPrice,Integer orderId) {
        //查询下单人
        User buy = userService.getById(buyId);
        userService.queryTeam(buy.getRefereeId(),payPrice);
//        userService.queryTeam(buy.getRefereeId(),payPrice);
        fundBalance(0,buy.getRefereeId(),payPrice,orderId);
    }




    /**
     * 根据上级节点查询
     * @param level 下级等级
     * @param pid 付节点
     */
    private void fundBalance(Integer level,Integer pid,BigDecimal payPrice,Integer orderId){
        logger.info("pid==="+pid+"----level=="+level);
//        System.out.println("pid==="+pid+"   ----level=="+level);



        User bean = userService.getById(pid);
//        TeamBean teamBean = userService.queryTeam(pid);

//        Integer integer = userService.selectInviteCodeNum(pid);
        if (null != bean) {
            Integer nowLev = bean.getLevel();
            String price = "0.08";//
            String str = "";

            if (nowLev >4){
                nowLev = 4;
            }
            int a = nowLev - level;
            if (a > 0) {
//            if (orderNum >1){
                BigDecimal ac = BigDecimalUtil.mul(new BigDecimal(price), new BigDecimal(a));
//                BigDecimal b = BigDecimalUtil.divide(ac,new BigDecimal("100"));
                userBillService.saveBill(str + "团队销售管理奖", ConfConstants.COMMISSION_TYPE, 1, BigDecimalUtil.mul(payPrice, ac), pid, ConfConstants.YJ_FLAG, orderId);
//            }
            }
            if (nowLev < 5) {
                //不是最大的等级，还可以找上面比自己大的
                if (a > 0) {
                    //当前等级大于
                    fundBalance(nowLev, bean.getRefereeId(), payPrice, orderId);
                } else {
                    fundBalance(level, bean.getRefereeId(), payPrice, orderId);
                }

            }
        }

    }

    @Override
    public void SensibleSettlement() {
//        String redisKey = TaskConstants.SENSIBLE_HANDLE;
//        List<Object> list = redisUtil.lRange(redisKey, 0, -1);
//        String localDate = LocalDate.now().toString();
//        if (null != list){
//            if (list.contains(localDate)){
//                logger.info(localDate+"权益卡重复结算了哦");
//                return ;
//            }
//        }
//
//
////        Double yesterdaySales = orderService.getYesterdaySales();
////        if (null == yesterdaySales || yesterdaySales.doubleValue() <= 0){
////            logger.info(localDate+"昨日订单销额为0");
////            return;
////        }
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.ge(User::getOrderNum,1);
//        List<User> users = userService.list(wrapper);
//
//
//        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
//        wrapper1.ge(User::getZtOrderNum,1);
//        wrapper1.ge(User::getOrderNum,1);
//        List<User> users1 = userService.list(wrapper1);
////        if (null == users || users.isEmpty()){
////            logger.info(localDate+"当前没有人可以分到权益卡");
////            return;
////        }
////        List<User> bList = new ArrayList<>();
//        if (null == users){
//            users = new ArrayList<>();
//        }
//        if (null == users1){
//            users1 = new ArrayList<>();
//        }
//        for (User user : users1){
//            for (int i = 0; i < user.getZtOrderNum(); i++) {
//                users.add(user);
//            }
////            if (selectUsrs(user.getUserId(),new BigDecimal(0))){
////                bList.add(user);
////            }
//        }
//
//        //算出平均人数收益
//        BigDecimal bigDecimal = BigDecimalUtil.divide(new BigDecimal(49),new BigDecimal(users.size()));
////
////        BigDecimal bigDecimal = BigDecimalUtil.divide(bsa,new BigDecimal(users.size()));
//        for (User user : users){
//            userBillService.saveBill("权益卡释放收益", ConfConstants.INTEGRAL_TYPE,1, bigDecimal, user.getUserId(),ConfConstants.YJ_FLAG,null);
//
//        }
//        LbSysConfigEntity configEntity = sysConfigService.selectSysConfig();
//        configEntity.setQykSf(BigDecimalUtil.addDouble(configEntity.getQykSf(),new BigDecimal(49)));
//        redisUtil.lPush(redisKey, localDate);
    }

    /**
     * 是否权益卡
     * @param bigDecimal
     * @param uid
     */
    private void sendQyk(BigDecimal bigDecimal,Integer uid,Integer orderId){
//
//        logger.info(orderId+"权益卡释放收益");
//        LbSysConfigEntity configEntity = sysConfigService.selectSysConfig();
//        if (configEntity.getQykSf().doubleValue()< 1314519){
//            userBillService.saveBill("权益卡释放收益", ConfConstants.INTEGRAL_TYPE,1, bigDecimal, uid,ConfConstants.YJ_FLAG,orderId);
//
//            configEntity.setQykSf(BigDecimalUtil.addDouble(configEntity.getQykSf(),bigDecimal));
//            sysConfigService.updateById(configEntity);
//        }


    }

    /**
     * 结算区域代理
     * @param orderId
     */
    private void regionAgent(Integer orderId,BigDecimal sy,String dw){
        OrderAddress orderAddress = addressService.getOrderId(orderId);
        if (null != orderAddress){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getRegionAgent,orderAddress.getRegionId());
            List<User> list = userService.list(userLambdaQueryWrapper);
            if (null != list && !list.isEmpty()){
                BigDecimal as = BigDecimalUtil.mul(sy,new BigDecimal(dw));
                userBillService.saveBill("区域服务中心补贴", ConfConstants.COMMISSION_TYPE,1,as , list.get(0).getUserId(),null,orderId);

            }
        }
    }

    /**
     * 结算市、省代理
     * @param orderId
     */
    private void cityAgent(Integer orderId,BigDecimal sy,String dw){
        OrderAddress orderAddress = addressService.getOrderId(orderId);
        if (null != orderAddress){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getCityAgent,orderAddress.getCityId());
            List<User> list = userService.list(userLambdaQueryWrapper);
            if (null != list && !list.isEmpty()){
                BigDecimal as = BigDecimalUtil.mul(sy,new BigDecimal(dw));
                userBillService.saveBill("市服务中心补贴", ConfConstants.COMMISSION_TYPE,1,as , list.get(0).getUserId(),null,orderId);

            }

            LambdaQueryWrapper<User> userLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper2.eq(User::getProvinceAgent,orderAddress.getProvinceId());
            List<User> list2 = userService.list(userLambdaQueryWrapper2);
            if (null != list2 && !list2.isEmpty()){
                BigDecimal as = BigDecimalUtil.mul(sy,new BigDecimal(dw));
                userBillService.saveBill("省服务中心补贴", ConfConstants.COMMISSION_TYPE,1,as , list2.get(0).getUserId(),null,orderId);

            }
        }
    }


//    private List<User> selectUsr(Integer userId){
//        User bean = userService.getById(userId);
//        BigDecimal a = orderService.getSumUserMoney(bean.getUserId());
//        if (a.doubleValue()> 3000){
//            return
//        }
//    }


    private boolean selectUsrs(Integer userId,BigDecimal money){
        User bean = userService.getById(userId);
       BigDecimal a = orderService.getSumUserMoney(bean.getUserId());
        money = BigDecimalUtil.addDouble(money,a);
       if (money.doubleValue()> 3000){
           return true;
       }else{
           if (null != bean.getAline() && bean.getAline().intValue() >0){
               User beanA = userService.getById(bean.getAline());
              if (selectUsrs(beanA.getUserId(), money)){
                  return true;
              }else {
                  if (null != bean.getBline() && bean.getBline().intValue() >0){
                      User beanB = userService.getById(bean.getBline());
                      if (selectUsrs(beanB.getUserId(), money)){
                          return true;
                      }else{
                          if (null != bean.getCline() && bean.getCline().intValue() >0){
                              User beanC = userService.getById(bean.getCline());
                              if (selectUsrs(beanC.getUserId(), money)){
                                  return true;
                              }else{
                                  return false;
                              }
                          }
                      }
                  }
              }
           }else{
               if (null != bean.getBline() && bean.getBline().intValue() >0){
                   User beanB = userService.getById(bean.getBline());
                   if (selectUsrs(beanB.getUserId(), money)){
                       return true;
                   }else{
                       return false;
                   }
               }
           }
       }
       return false;
    }


    private boolean goGpOderInfo(Order storeOrder, List<OrderProduct> orderInfoList,User walletInfo,Integer orderId,Integer payType){
        Integer uid = storeOrder.getUserId();
        BigDecimal payPrice = storeOrder.getPayPrice();
        if (lineUpService.getLineNum(storeOrder.getShopSupplierId()) > 0){
            LambdaQueryWrapper<LbLineUp> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LbLineUp::getOrderId,storeOrder.getOrderNo());
//            wrapper.eq(LbLineUp::getPid,storeOrder.getShopSupplierId());
            List<LbLineUp> liUp = lineUpService.list(wrapper);
            if (null == liUp || liUp.isEmpty()){
                LbLineUp line = new LbLineUp();
                line.setCreateTime(new Date());
                line.setTotal(BigDecimalUtil.mul(storeOrder.getPayPrice(),new BigDecimal("1.0")));
                line.setUid(uid);
                line.setPrice(storeOrder.getPayPrice());
                line.setOrderId(storeOrder.getOrderNo());
                line.setPid(storeOrder.getShopSupplierId());
                if (payType == 10){
                    if(!lineUpService.save(line)){
                        logger.info(storeOrder.getOrderId()+"公排异常");
                        throw new BusinessException("公排订单异常");

                    }
                }

            }

        }

//        //添加分红池
//        LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
//        BigDecimal xDa = new BigDecimal(0.05);//下单百分之5分红池
//        BigDecimal fhPrice = BigDecimalUtil.mul(payPrice, xDa);
//        lbSysConfigEntity.setDividendPool(BigDecimalUtil.addDouble(fhPrice,lbSysConfigEntity.getDividendPool()));
//        sysConfigService.updateById(lbSysConfigEntity);
//        userBillService.addBillRecord("消费分红贡献",ConfConstants.DIVIDEND_POOL,1,fhPrice,uid,2);


//
        BigDecimal sy = new BigDecimal("0");
        BigDecimal dyPrice = null;
        for (OrderProduct bean : orderInfoList){
            Product productServiceById = productService.getById(bean.getProductId());
            //计算产品的波比收益
            sy = BigDecimalUtil.mul(bean.getTotalPayPrice(),productServiceById.getRate());
//            sy = BigDecimalUtil.addDouble(sy,BigDecimalUtil.mul(bob,new BigDecimal(bean.getPayNum())));
        }
        regionAgent(storeOrder.getOrderId(),payPrice,"0.05");
        //查询收益中的公排订单
        LbLineUp status1 = lineUpService.getStatus1(storeOrder.getShopSupplierId());
        if (null != status1){
            BigDecimal ts = BigDecimalUtil.addDouble(status1.getIncome(),sy);
            if (ts.doubleValue() >= status1.getTotal().doubleValue()){
                dyPrice = BigDecimalUtil.subDouble(ts,status1.getTotal());
                status1.setStatus(2);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,BigDecimalUtil.subDouble(status1.getTotal(),status1.getIncome()) , status1.getUid(),null,orderId);
//                LbLineUp lbLineUp = lbLineUpService.setUpOrder();
                status1.setIncome(status1.getTotal());
                lineUpService.updateById(status1);
                if (dyPrice.doubleValue() > 0){
                    Gp(dyPrice,orderId,storeOrder.getShopSupplierId());
                }

            }else{
                status1.setIncome(ts);
                lineUpService.updateById(status1);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,sy , status1.getUid(),null,orderId);

            }
        }else{

            Gp(sy,orderId,storeOrder.getShopSupplierId());
        }


        if (lineUpService.getLineNum(storeOrder.getShopSupplierId()) == 0){
            LambdaQueryWrapper<LbLineUp> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LbLineUp::getOrderId,storeOrder.getOrderNo());
//            wrapper.eq(LbLineUp::getPid,storeOrder.getShopSupplierId());
            List<LbLineUp> liUp = lineUpService.list(wrapper);
            if (null == liUp || liUp.isEmpty()) {
                LbLineUp line = new LbLineUp();
                line.setCreateTime(new Date());
                line.setPrice(storeOrder.getPayPrice());
                line.setTotal(BigDecimalUtil.mul(storeOrder.getPayPrice(), new BigDecimal("1.0")));
                line.setUid(uid);
                line.setPid(storeOrder.getShopSupplierId());
                line.setOrderId(storeOrder.getOrderNo());
                if (payType == 10) {
                    if (!lineUpService.save(line)) {
                        logger.info(storeOrder.getOrderId() + "公排异常");
                        throw new BusinessException("公排订单异常");

                    }
                }
            }
        }






        /**
         * 确认收货送积分
         */

        String where = "paid = 1 and refund_status = 0 and uid = "+uid;
        //首单消费送积分,用户在前5000个才送积分
        walletInfo.setPoints(BigDecimalUtil.addDouble(new BigDecimal(walletInfo.getPoints()),payPrice).intValue());
        walletInfo.setAllAv(BigDecimalUtil.addDouble(walletInfo.getAllAv(),payPrice));
//        walletInfo.setFirstPay(BigDecimalUtil.addDouble(userSave.getFirstPay(),payPrice));
            userService.updateById(walletInfo);
//        }




        //直推直接算提成
        BigDecimal scale = new BigDecimal("0.1");//直推提成10%
        BigDecimal price = BigDecimalUtil.mul(payPrice, scale);
        userBillService.saveBill("直推奖励", ConfConstants.COMMISSION_TYPE,1, price, walletInfo.getRefereeId(),ConfConstants.YJ_FLAG,orderId);
//        }
//         marketPromotion(storeOrder);


        //查询商家信息，查找商家推荐人，进行每一笔订单的奖励
        Supplier supplier = supplierService.getById(storeOrder.getShopSupplierId());
        if (null != supplier){
            //计算成本给商家
            BigDecimal bs = BigDecimalUtil.mul(storeOrder.getPayPrice(),supplier.getCostRate());
            supplier.setMoney(BigDecimalUtil.addDouble(supplier.getMoney(),bs));
            supplierService.updateById(supplier);
            userBillService.saveBill("店铺补贴", ConfConstants.COMMISSION_TYPE,1, bs, supplier.getUserId(),ConfConstants.YJ_FLAG,orderId);
            if ( null != supplier.getTjPhone()){
                User byAccount = userService.getByAccount(supplier.getTjPhone());
                if (null != byAccount) {
                    //直推直接算提成
                    BigDecimal tshop = new BigDecimal(0.03);//推商家拿%2订单奖
                    BigDecimal uSy = BigDecimalUtil.mul(payPrice, tshop);
                    userBillService.saveBill("商家推荐产品收益奖", ConfConstants.COMMISSION_TYPE, 1, uSy, byAccount.getUserId(), ConfConstants.YJ_FLAG, orderId);
                }
            }

        }
//        rangeReward(uid,storeOrder.getPayPrice(),orderId);
//        User ac = userService.getById(uid);
//        jsAst(sy,ac.getPid(),orderId);

        return true;
    }

    /**
     * 结算20成收益
     */
    private void jsAst(BigDecimal price,Integer pid,Integer orderId){
        int a = 0;
        User byId = userService.getById(pid);
        if (null != byId){
            a ++;
            BigDecimal ac = BigDecimalUtil.mul(price, new BigDecimal("0.01"));
//                BigDecimal b = BigDecimalUtil.divide(ac,new BigDecimal("100"));
            userBillService.saveBill("市场推广收益奖", ConfConstants.COMMISSION_TYPE, 1, ac, pid, ConfConstants.YJ_FLAG, orderId);

            if (a <20){
                jsAst(price,pid,orderId);
            }
        }
    }



    private boolean threeMode(Order storeOrder, User walletInfo,Integer orderId,Integer payType){

        Integer uid = storeOrder.getUserId();
        BigDecimal payPrice = storeOrder.getPayPrice();
        BigDecimal sy = BigDecimalUtil.mul(payPrice,new BigDecimal(0.2));
//        //添加分红池
        LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
//        BigDecimal xDa = new BigDecimal(0.05);//下单百分之5分红池
//        BigDecimal fhPrice = BigDecimalUtil.mul(payPrice, xDa);
//        lbSysConfigEntity.setLottery(BigDecimalUtil.addDouble(lbSysConfigEntity.getLottery(),sy));
////        lbSysConfigEntity.setWelfare(BigDecimalUtil.addDouble(welfare,lbSysConfigEntity.getWelfare()));
//        lbSysConfigEntity.setDividendPool(BigDecimalUtil.addDouble(fhPrice,lbSysConfigEntity.getDividendPool()));
//        sysConfigService.updateById(lbSysConfigEntity);
//        logger.info(orderId+"更新分红池");
//        userBillService.addBillRecord("消费分红贡献",ConfConstants.DIVIDEND_POOL,1,fhPrice,uid,2,orderId);
        BigDecimal pool1 = BigDecimalUtil.mul(payPrice,new BigDecimal(0.1));//总代理分红池
        lbSysConfigEntity.setPool1(BigDecimalUtil.addDouble(lbSysConfigEntity.getPool1(),pool1));
        lbSysConfigEntity.setPool2(BigDecimalUtil.addDouble(lbSysConfigEntity.getPool2(),sy));
        sysConfigService.updateById(lbSysConfigEntity);
        LbUserWalletEntity qb = walletService.getUserWalletInfo(uid);
        qb.setDevote(BigDecimalUtil.addDouble(qb.getDevote(),BigDecimalUtil.mul(payPrice,new BigDecimal(5))));
        if (qb.getDjMoney().doubleValue() >0){
            logger.info(orderId+"佣金冻结结算处理");
            BigDecimal a = null;
            if (qb.getDevote().doubleValue() > qb.getDjMoney().doubleValue()){

                //释放冻结佣金
                a = qb.getDjMoney();
                qb.setDjMoney(new BigDecimal(0));
                qb.setDevote(BigDecimalUtil.subDouble(qb.getDevote(),qb.getDjMoney()));

            }else{
                BigDecimal b = BigDecimalUtil.subDouble(qb.getDjMoney(),qb.getDevote());
                a = qb.getDevote();
                qb.setDjMoney(b);
                qb.setDevote(new BigDecimal(0));
            }

//            userBillService.saveBill("冻结佣金释放",ConfConstants.COMMISSION_TYPE,1,a,uid,ConfConstants.YJ_FLAG, orderId);
            if(a.doubleValue() >0) {
                BigDecimal aa = BigDecimalUtil.mul(a, new BigDecimal(1));
                BigDecimal bb = BigDecimalUtil.mul(a, new BigDecimal(0.1));
                BigDecimal total = BigDecimalUtil.addDouble(qb.getMoney(), aa);
//                    walletInfo.setEntityMoney(BigDecimalUtil.addDouble(walletInfo.getEntityMoney(), a));
                qb.setTotalMoney(BigDecimalUtil.addDouble(qb.getTotalMoney(), aa));
//                qb.setIntegral(BigDecimalUtil.addDouble(qb.getIntegral(),bb));
                qb.setMoney(total);
                userBillService.addBillRecord("冻结佣金释放", ConfConstants.COMMISSION_TYPE, 1, a, uid, 2,orderId);
            }
            logger.info(orderId+"佣金冻结结算处理完成");
        }
        walletService.updateById(qb);

//

        /**
         * 拿出百分20%作为公排收益
         *
         */

        BigDecimal dyPrice = null;
        LbLineUp status1 = lineUpService.getStatus1(storeOrder.getShopSupplierId());
        if (null != status1){
            BigDecimal ts = BigDecimalUtil.addDouble(status1.getIncome(),sy);
            if (ts.doubleValue() >= status1.getTotal().doubleValue()){
                dyPrice = BigDecimalUtil.subDouble(ts,status1.getTotal());
                status1.setStatus(2);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,BigDecimalUtil.subDouble(status1.getTotal(),status1.getIncome()) , status1.getUid(),null,orderId);
//                LbLineUp lbLineUp = lbLineUpService.setUpOrder();
                status1.setIncome(status1.getTotal());
                lineUpService.updateById(status1);
                if (dyPrice.doubleValue() > 0){
                    Gp(dyPrice,orderId,storeOrder.getShopSupplierId());
                }

            }else{
                status1.setIncome(ts);
                lineUpService.updateById(status1);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,sy , status1.getUid(),null,orderId);

            }
        }else{

            Gp(sy,orderId,storeOrder.getShopSupplierId());
        }


//
        userService.updateById(walletInfo);
//        }

        regionAgent(storeOrder.getOrderId(),payPrice,"0.05");
        cityAgent(storeOrder.getOrderId(),payPrice,"0.02");
        //直推直接算提成
        BigDecimal scale = new BigDecimal(0.1);//直推提成10%
        BigDecimal price = BigDecimalUtil.mul(payPrice, scale);
        logger.info(orderId+"直推奖励结算哦");
        userBillService.saveBill("直推奖励", ConfConstants.COMMISSION_TYPE,1, price, walletInfo.getRefereeId(),ConfConstants.YJ_FLAG,orderId);

//        }




        //查询商家信息，查找商家推荐人，进行每一笔订单的奖励
        Supplier supplier = supplierService.getById(storeOrder.getShopSupplierId());
        if (null != supplier){
            //计算成本给商家
            BigDecimal bs = BigDecimalUtil.mul(storeOrder.getPayPrice(),supplier.getCostRate());
            supplier.setMoney(BigDecimalUtil.addDouble(supplier.getMoney(),bs));
            supplierService.updateById(supplier);
            userBillService.saveBill("店铺补贴", ConfConstants.COMMISSION_TYPE,1, bs, supplier.getUserId(),ConfConstants.YJ_FLAG,orderId);
            if ( null != supplier.getTjPhone()){
                User byAccount = userService.getByAccount(supplier.getTjPhone());
                if (null != byAccount) {
                    //直推直接算提成
                    BigDecimal tshop = new BigDecimal(0.03);//推商家拿%2订单奖
                    BigDecimal uSy = BigDecimalUtil.mul(payPrice, tshop);
                    userBillService.saveBill("商家推荐产品收益奖", ConfConstants.COMMISSION_TYPE, 1, uSy, byAccount.getUserId(), ConfConstants.YJ_FLAG, orderId);
                }
            }

        }
        LbLotteryOrder lbLotteryOrder = new LbLotteryOrder();
        lbLotteryOrder.setOrderNo(storeOrder.getOrderNo());
        lbLotteryOrder.setUid(uid);
        lbLotteryOrder.setMoney(sy);
        lbLotteryOrder.setCreateTime(new Date());
      boolean a=  lotteryOrderService.save(lbLotteryOrder);
        List<LbLotteryOrder> lotteryList = lotteryOrderService.getLotteryList();
        if (null != lotteryList && !lotteryList.isEmpty()){
            if (lbSysConfigEntity.getLotteryNum() <= lotteryList.size()){
                Object lotteryOrder = redisUtil.get("LotteryOrder");
                if (null == lotteryOrder){
                    redisUtil.set("LotteryOrder", lotteryList);
                }

            }
        }


        return true;
    }

    /**
     * 购买产品送权益
     * @param qb
     * @param qyNum
     */
    private void goodQyNum( LbUserWalletEntity qb,BigDecimal qyNum){
        if (null != qyNum && qyNum.doubleValue() >0){
            qb.setScore(BigDecimalUtil.addDouble(qb.getScore(),qyNum));
        }

    }

    private boolean fourMode(Order storeOrder, List<OrderProduct> orderInfoList, User walletInfo,Integer orderId,Integer payType){

        Integer uid = storeOrder.getUserId();
        walletInfo = userService.getById(uid);
        BigDecimal payPrice = storeOrder.getPayPrice();
        BigDecimal sy = BigDecimalUtil.mul(payPrice,new BigDecimal(0.05));
        //添加分红池
//        LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
////        BigDecimal xDa = new BigDecimal(0.05);//下单百分之5分红池
////        BigDecimal fhPrice = BigDecimalUtil.mul(payPrice, xDa);
//        lbSysConfigEntity.setLottery(BigDecimalUtil.addDouble(lbSysConfigEntity.getLottery(),sy));
////        lbSysConfigEntity.setWelfare(BigDecimalUtil.addDouble(welfare,lbSysConfigEntity.getWelfare()));
//        BigDecimal welfare = BigDecimalUtil.mul(payPrice, new BigDecimal(0.01));
//        lbSysConfigEntity.setWelfare(BigDecimalUtil.addDouble(welfare,lbSysConfigEntity.getWelfare()));
////        lbSysConfigEntity.setDividendPool(BigDecimalUtil.addDouble(fhPrice,lbSysConfigEntity.getDividendPool()));
//        sysConfigService.updateById(lbSysConfigEntity);
//        logger.info(orderId+"更新分红池");
//        userBillService.addBillRecord("消费分红贡献",ConfConstants.DIVIDEND_POOL,1,fhPrice,uid,2,orderId);

            Product productServiceById = productService.getById(orderInfoList.get(0).getProductId());
            if (null != productServiceById){
                if (null != productServiceById.getLevel4()){
                    if (null == walletInfo.getLevel4()){
                        walletInfo.setLevel4(productServiceById.getLevel4());
                        if (productServiceById.getLevel4()>3){
                            walletInfo.setLevelControl(1);
                        }
                    }else{
                        if (productServiceById.getLevel4() > walletInfo.getLevel4()){
                            walletInfo.setLevel4(productServiceById.getLevel4());
                            if (productServiceById.getLevel4()>3){
                                walletInfo.setLevelControl(1);
                            }
                        }
                    }
                }
            }

        userService.updateById(walletInfo);
        LbUserWalletEntity qb = walletService.getUserWalletInfo(uid);
        qb.setDevote(BigDecimalUtil.addDouble(qb.getDevote(),BigDecimalUtil.mul(payPrice,new BigDecimal(5))));
//        goodQyNum(qb,productServiceById.getQyNum());
        if (qb.getDjMoney().doubleValue() >0){
            logger.info(orderId+"佣金冻结结算处理");
            BigDecimal a = null;
            if (qb.getDevote().doubleValue() > qb.getDjMoney().doubleValue()){

                //释放冻结佣金
                a = qb.getDjMoney();
                qb.setDjMoney(new BigDecimal(0));
                qb.setDevote(BigDecimalUtil.subDouble(qb.getDevote(),qb.getDjMoney()));

            }else{
                BigDecimal b = BigDecimalUtil.subDouble(qb.getDjMoney(),qb.getDevote());
                a = qb.getDevote();
                qb.setDjMoney(b);
                qb.setDevote(new BigDecimal(0));
            }

//            userBillService.saveBill("冻结佣金释放",ConfConstants.COMMISSION_TYPE,1,a,uid,ConfConstants.YJ_FLAG, orderId);
            if(a.doubleValue() >0) {
                BigDecimal aa = BigDecimalUtil.mul(a, new BigDecimal(1));
                BigDecimal bb = BigDecimalUtil.mul(a, new BigDecimal(0.1));
                BigDecimal total = BigDecimalUtil.addDouble(qb.getMoney(), aa);
//                    walletInfo.setEntityMoney(BigDecimalUtil.addDouble(walletInfo.getEntityMoney(), a));
                qb.setTotalMoney(BigDecimalUtil.addDouble(qb.getTotalMoney(), aa));
//                qb.setIntegral(BigDecimalUtil.addDouble(qb.getIntegral(),bb));
                qb.setMoney(total);
                userBillService.addBillRecord("冻结佣金释放", ConfConstants.COMMISSION_TYPE, 1, a, uid, 2,orderId);
            }
            logger.info(orderId+"佣金冻结结算处理完成");
        }
        walletService.updateById(qb);

//


        /**
         * 拿出百分5%作为公排收益
         *
         */

        BigDecimal dyPrice = null;
        LbLineUp status1 = lineUpService.getStatus1(storeOrder.getShopSupplierId());
        if (null != status1){
            BigDecimal ts = BigDecimalUtil.addDouble(status1.getIncome(),sy);
            if (ts.doubleValue() >= status1.getTotal().doubleValue()){
                dyPrice = BigDecimalUtil.subDouble(ts,status1.getTotal());
                status1.setStatus(2);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,BigDecimalUtil.subDouble(status1.getTotal(),status1.getIncome()) , status1.getUid(),null,orderId);
//                LbLineUp lbLineUp = lbLineUpService.setUpOrder();
                status1.setIncome(status1.getTotal());
                lineUpService.updateById(status1);
                if (dyPrice.doubleValue() > 0){
                    Gp(dyPrice,orderId,storeOrder.getShopSupplierId());
                }

            }else{
                status1.setIncome(ts);
                lineUpService.updateById(status1);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,sy , status1.getUid(),null,orderId);

            }
        }else{

            Gp(sy,orderId,storeOrder.getShopSupplierId());
        }


//
//        userService.updateById(walletInfo);
//        }

        regionAgent(storeOrder.getOrderId(),payPrice,"0.02");
        cityAgent(storeOrder.getOrderId(),payPrice,"0.02");
        //直推直接算提成
        BigDecimal scale = new BigDecimal(0.1);//直推提成10%
        BigDecimal price = BigDecimalUtil.mul(payPrice, scale);
        logger.info(orderId+"直推奖励结算哦");
        userBillService.saveBill("直推奖励", ConfConstants.COMMISSION_TYPE,1, price, walletInfo.getRefereeId(),ConfConstants.YJ_FLAG,orderId);

//        }




        //查询商家信息，查找商家推荐人，进行每一笔订单的奖励
        Supplier supplier = supplierService.getById(storeOrder.getShopSupplierId());
        if (null != supplier){
            //计算成本给商家
            BigDecimal bs = BigDecimalUtil.mul(storeOrder.getPayPrice(),supplier.getCostRate());
            supplier.setMoney(BigDecimalUtil.addDouble(supplier.getMoney(),bs));
            supplierService.updateById(supplier);
            userBillService.saveBill("店铺补贴", ConfConstants.COMMISSION_TYPE,1, bs, supplier.getUserId(),ConfConstants.YJ_FLAG,orderId);
            if ( null != supplier.getTjPhone()){
                User byAccount = userService.getByAccount(supplier.getTjPhone());
                if (null != byAccount) {
                    //直推直接算提成
                    BigDecimal tshop = new BigDecimal(0.03);//推商家拿%2订单奖
                    BigDecimal uSy = BigDecimalUtil.mul(payPrice, tshop);
                    userBillService.saveBill("商家推荐产品收益奖", ConfConstants.COMMISSION_TYPE, 1, uSy, byAccount.getUserId(), ConfConstants.YJ_FLAG, orderId);
                }
            }

        }

        if (null != walletInfo.getRefereeId()){
            jsManagerMoney(walletInfo.getRefereeId(),0,payPrice);
        }
        jsLevel(walletInfo.getUserId());


        return true;
    }

    /**
     * 计算等级
     * @param pid
     */
    private void jsLevel(Integer pid){
        User byId = userService.getById(pid);
        if (null != byId && byId.getZtOrderNum() >=3){
//
//        BigDecimal decimal = new BigDecimal(0);
//        if (null != byId.getAline()){
//            BigDecimal a = userService.getAline(byId.getAline());
//            if (null != a && a.doubleValue() >0){
//                decimal=  BigDecimalUtil.addDouble(decimal,a);
//            }
//        }
//        if (null != byId.getBline()){
//            BigDecimal a = userService.getAline(byId.getBline());
//            if (null != a && a.doubleValue() >0){
//                decimal=  BigDecimalUtil.addDouble(decimal,a);
//            }
//        }
//        if (null != byId.getCline()){
//            BigDecimal a = userService.getAline(byId.getCline());
//            if (null != a && a.doubleValue() >0){
//                decimal=  BigDecimalUtil.addDouble(decimal,a);
//            }
//        }

            BigDecimal decimal =   userService.getYjMoney(pid);

        int level4 = 0;
        if (decimal.doubleValue() >=2000 && decimal.doubleValue() < 10000){
            level4 = 1;
        }else if (decimal.doubleValue() >=10000 && decimal.doubleValue() < 50000){
            level4 = 2;
        }else if (decimal.doubleValue() >=50000 && decimal.doubleValue() < 200000){
            level4 = 3;
        }else if (decimal.doubleValue() >=20000 && decimal.doubleValue() < 500000){
            level4 = 4;
        }
        else if (decimal.doubleValue() >=500000){
            level4 = 5;
        }
        if (null == byId.getLevel4()){
            byId.setLevel4(-1);
        }
        if (byId.getLevel4() < level4){
            byId.setLevel4(level4);
            if (level4 >3){
                byId.setLevelControl(1);
            }
            userService.updateById(byId);
        }
    }
        if (byId != null){
            if (null != byId.getRefereeId()){
                jsLevel(byId.getRefereeId());
            }

        }
    }
    //结算团队管理奖
    private void jsManagerMoney(int pid,int level,BigDecimal payMoney){
        User byId = userService.getById(pid);
        double bs = 0.1;
        if (byId !=null ){
            int lev =-1;
            if (null == byId.getLevel4()){
                lev = -1;
            }else{
                lev = byId.getLevel4();
            }
            int a = lev - level;
            if (lev > level){
                level = lev;
            }
            if ( a >0){
                double cs = bs*a;
                BigDecimal bigDecimal = BigDecimalUtil.mul(new BigDecimal(cs),payMoney);
                userBillService.saveBill("管理奖", ConfConstants.COMMISSION_TYPE,1, bigDecimal,pid,ConfConstants.YJ_FLAG,null);
                if (null!=byId.getRefereeId()){
                    User pjUser = userService.getById(byId.getRefereeId());
                    if (null !=pjUser && null != pjUser.getLevel4() && pjUser.getLevel4()>0 && pjUser.getLevel4()<= byId.getLevel4()) {
                        BigDecimal pjMoney = BigDecimalUtil.mul(new BigDecimal(0.2), bigDecimal);
                        userBillService.saveBill("平级奖", ConfConstants.COMMISSION_TYPE, 1, pjMoney, byId.getRefereeId(), ConfConstants.YJ_FLAG, null);
                    }
                }
            }

            if (null!=byId.getRefereeId()){
                jsManagerMoney(byId.getRefereeId(),level,payMoney);
            }

        }
    }

    private void clGpMeth(BigDecimal sy,Integer orderId){
        /**
         * 公排收益
         *
         */

        BigDecimal dyPrice = null;
        LbLineUp status1 = lineUpService.getStatus1(null);
        if (null != status1){
            BigDecimal ts = BigDecimalUtil.addDouble(status1.getIncome(),sy);
            if (ts.doubleValue() >= status1.getTotal().doubleValue()){
                dyPrice = BigDecimalUtil.subDouble(ts,status1.getTotal());
                status1.setStatus(2);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,BigDecimalUtil.subDouble(status1.getTotal(),status1.getIncome()) , status1.getUid(),null,orderId);
//                LbLineUp lbLineUp = lbLineUpService.setUpOrder();
                status1.setIncome(status1.getTotal());
                lineUpService.updateById(status1);
                if (dyPrice.doubleValue() > 0){
                    Gp(dyPrice,orderId,null);
                }

            }else{
                status1.setIncome(ts);
                lineUpService.updateById(status1);
                userBillService.saveBill("消费分红收益", ConfConstants.COMMISSION_TYPE,1,sy , status1.getUid(),null,orderId);

            }
        }else{

            Gp(sy,orderId,null);
        }
    }




//    /**
//     * 计算等级
//     * @param pid
//     */
//    private void jsLevel(Integer pid){
//        User byId = userService.getById(pid);
//        if (null == byId.getLevel4()){
//            byId.setLevel4(-1);
//        }
//        if (null != byId && byId.getZtOrderNum() >=3){
//
//            if (null != byId.getAline() && null != byId.getBline() &&null != byId.getCline()){
//                Integer a =userService.getAllDlNum(byId.getAline());
//                if (a >0){
//                    Integer b =userService.getAllDlNum(byId.getBline());
//                    if (b >0){
//                        Integer c =userService.getAllDlNum(byId.getCline());
//                        if (c >0){
//                            byId.setLevel4(5);
//                        }
//                    }
//                }else{
//                    a =userService.getGjdlNum(byId.getAline());
//                    if (a >0){
//                        Integer b =userService.getGjdlNum(byId.getBline());
//                        if (b >0){
//                            Integer c =userService.getGjdlNum(byId.getCline());
//                            if (c >0){
//                                byId.setLevel4(4);
//                            }
//                        }
//                    }
//                }
//            }
//
//            BigDecimal decimal = new BigDecimal(0);
//            if (byId.getLevel4() <3) {
//                if (null != byId.getAline()) {
//                    BigDecimal a = userService.getAline(byId.getAline());
//                    if (null != a && a.doubleValue() > 0) {
//                        decimal = BigDecimalUtil.addDouble(decimal, a);
//                    }
//                }
//                if (null != byId.getBline()) {
//                    BigDecimal a = userService.getAline(byId.getBline());
//                    if (null != a && a.doubleValue() > 0) {
//                        decimal = BigDecimalUtil.addDouble(decimal, a);
//                    }
//                }
//                if (null != byId.getCline()) {
//                    BigDecimal a = userService.getAline(byId.getCline());
//                    if (null != a && a.doubleValue() > 0) {
//                        decimal = BigDecimalUtil.addDouble(decimal, a);
//                    }
//                }
//
//
//                int level4 = 0;
//                if (decimal.doubleValue() >= 10000 && decimal.doubleValue() < 100000) {
//                    level4 = 1;
//                } else if (decimal.doubleValue() >= 100000 && decimal.doubleValue() < 500000) {
//                    level4 = 2;
//                } else if (decimal.doubleValue() >= 500000) {
//                    level4 = 3;
//                }
//
//
//                if (byId.getLevel4() < level4) {
//                    byId.setLevel4(level4);
//                }
//                userService.updateById(byId);
//            }
//        }
//        if (byId != null){
//            if (null != byId.getPid()){
//                jsLevel(byId.getPid());
//            }
//
//        }
//    }

}
